from django.shortcuts import render, reverse
from index.models import Note
from django.http import HttpResponseRedirect, HttpResponse


# 首页笔记列表
def index_view(request):
    id = request.session.get("uid") or request.COOKIES.get("uid")

    if id:
        index_data = {}
        index_data['my_notes'] = Note.objects.filter(user_id=id)
        return render(request, "index/index.html", {"index_data": index_data})


# 添加新笔记
def index_add_note(request):
    if request.method == 'GET':
        return render(request, "index/add.html")
    elif request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']

        id = request.session.get("uid") or request.COOKIES.get("uid")

        Note.objects.create(title=title, content=content, user_id=id)

        return HttpResponseRedirect(reverse(index_view))


# 删除某条笔记
def index_delete_note(request, id):
    uid = request.session.get("uid") or request.COOKIES.get("uid")
    if uid:
        Note.objects.get(id=id).delete()
        return HttpResponseRedirect(reverse(index_view))
    else:
        return HttpResponse("无权限, 请登录")


# 修改笔记
def index_update_note(request, id):
    uid = request.session.get("uid") or request.COOKIES.get("uid")
    if uid:
        note = Note.objects.get(id=id)
        if request.method == 'GET':
            return render(request, "index/update.html", {'note': note})
        elif request.method == 'POST':
            note.title = request.POST['title']
            note.content = request.POST['content']
            note.save()
            return HttpResponseRedirect(reverse(index_view))
    else:
        return HttpResponse("无权限, 请登录")
